<?php

namespace app\admin\model;


/**
 * Author:Jack Wang
 * Time:2018-11-05 15:30:44
 * Describe:图纸模型
 * Class Drawing
 * @package app\admin\model
 */
class Drawing extends Base
{
    protected $autoWriteTimestamp = true;//开启自动添加时间戳

    protected $auto = ["attrs","substation_name"];

    protected $insert = ['create_id','create_nick_name'];//添加插入


    //获取图集
    public function getDrawingAtlasAttr($value){
        return json_decode($value,true);
    }

    //添加人ID
    protected function setCreateIdAttr()
    {
        return $this->admin["admin_id"];
    }

    //添加人名称
    protected function setCreateNickNameAttr()
    {
        return !empty($this->admin["nick_name"]) ? $this->admin["nick_name"] : $this->admin["admin_name"];
    }

    //添加修改属性自动转化
    protected function setAttrsAttr($value)
    {
        $str = '';
        if(!empty($value)) {
            if(is_array($value)) {
                $str = ArrayToStr($str);
            }else{
                $str = $value;
            }
        }
        return $str;
    }

    //auto，分站名称
    protected function setSubstationNameAttr($value,$data)
    {
        if(!empty($data["substation_id"])) {
            $Substation = new Substation();//分站类
            return $Substation->getFieldValue("substation_id", $data["substation_id"], "substation_name");
        }else{
            //接口更新图纸
            return $this->where("no",$data["no"])->where("no2",$data["no2"])->value("substation_name");
        }
    }

    //获取属性数组
    public function getAttrDataAttr($value,$data)
    {
        return StrToArray($data["attrs"]);
    }

    //编号别名
    public function getNo2NameAttr($value,$data)
    {
        $Config = new Config();
        return $Config->getConfigName($data["no2"]);
    }

    //查看该图纸和方案是否存在
    public function checkNO($no,$no2,$drawing_id = 0){
        return $this->where("no",$no)->where("no2",$no2)->where("drawing_id","neq",$drawing_id)->count();
    }

    //图纸列表
    public function drawingList($keyword = "",$cate = "",$layct = ""){
        return $this
            ->where(function ($q)use ($keyword){
                if(!empty($keyword)){
                    //模糊查找支持标题和编号
                    $q->whereOr("no",'like','%'.$keyword.'%')->whereOr("topic",'like','%'.$keyword.'%');
                }
            })
            ->where(function ($q)use ($cate){
                if(!empty($cate)){
                    //分类查找
                    $q->where("cate",$cate);
                }
            })
            ->where(function ($q)use ($layct){
                if(!empty($layct)){
                    //楼层查找
                    $fristLayct = substr($layct, 0, 1);//获取第一个字符串,判断条件
                    if((int)$fristLayct > 0){//是否3层以上
                        $q->where("layct",$layct);
                    }else{
                        $q->where("layct",$fristLayct,substr($layct, 1, strlen($layct) - 1));
                    }
                }
            })
            ->where(function ($q){
                if(!empty($this->substations)){//是否设置了当前网站
                    $q->where("substation_id",$this->substations);
                }else{
                    if($this->admin["group_id"] != config("SuperAdminGroupId")) {//是否超级管理员
                        $arr = [];
                        $Substation = new Substation();//分站类
                        $userList = $Substation->userList();//获取分站集合
                        foreach ($userList as $val){
                            $arr[] = $val['substation_id'];
                        }
                        $q->where("substation_id","in",$arr);
                    }
                }
            })
            ->orderRaw("substation_id ASC,if(is_shel='1',1,0) DESC,if(is_top='1',1,0) DESC,update_time DESC")
            ->page($this->after_page)
            ->limit($this->after_limit)
            ->select();
    }

    /**
     * Author:Jack Wang
     * Time:2018-11-09 10:27:51
     * Describe:图纸列表总数
     * @param string $keyword
     * @param string $cate
     * @param string $layct
     * @return int|string
     */
    public function drawingListCount($keyword = "",$cate = "",$layct = ""){
        return $this
            ->where(function ($q)use ($keyword){
                if(!empty($keyword)){
                    //模糊查找支持标题和编号
                    $q->whereOr("no",'like','%'.$keyword.'%')->whereOr("topic",'like','%'.$keyword.'%');
                }
            })
            ->where(function ($q)use ($cate){
                if(!empty($cate)){
                    //分类查找
                    $q->where("cate",$cate);
                }
            })
            ->where(function ($q)use ($layct){
                if(!empty($layct)){
                    //楼层查找
                    $fristLayct = substr($layct, 0, 1);//获取第一个字符串,判断条件
                    if((int)$fristLayct > 0){//是否3层以上
                        $q->where("layct",$layct);
                    }else{
                        $q->where("layct",$fristLayct,substr($layct, 1, strlen($layct) - 1));
                    }
                }
            })
            ->where(function ($q){
                if(!empty($this->substations)){//是否设置了当前网站
                    $q->where("substation_id",$this->substations);
                }else{
                    if($this->admin["group_id"] != config("SuperAdminGroupId")) {//是否超级管理员
                        $arr = [];
                        $Substation = new Substation();//分站类
                        $userList = $Substation->userList();//获取分站集合
                        foreach ($userList as $val){
                            $arr[] = $val['substation_id'];
                        }
                        $q->where("substation_id","in",$arr);
                    }
                }
            })
            ->count();
    }

    /**
     * Author:Jack Wang
     * Time:2018-11-13 16:16:30
     * Describe:根据编号获取方案列表
     * @param $no
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getNoProgrammeList($no){
        return $this
            ->alias("a")
            ->field([
                "b.config_id",
                "b.config_name"
            ])
            ->join($this->prefix."config b","a.no2 = b.config_id")
            ->where("a.no",$no)
            ->group("a.no")
            ->select();
    }

    //验证是否有权限操作
    public function checkSave($drawing_id,$substation_id){
        $is = [false,false];//验证标识
        if($this->admin["group_id"] != config("SuperAdminGroupId")) {//是否超级管理员
            $Substation = new Substation();//分站类
            $userList = $Substation->userList();//获取分站集合
            $drawing_substation_id = $this->where("drawing_id",$drawing_id)->value("substation_id");//获取原分站ID
            foreach ($userList as $val){//遍历分站集合
                if(!empty($drawing_id)) {//修改验证
                    if ($drawing_substation_id == $val["substation_id"]) {
                        $is[0] = true;
                    }
                }else{
                    //添加不验证
                    $is[0] = true;
                }
                if(!empty($substation_id)) {//添加修改验证
                    if ($substation_id == $val["substation_id"]) {
                        $is[1] = true;
                    }
                }else{
                    //删除不验证
                    $is[1] = true;
                }
            }
        }else{
            $is = [true,true];
        }
        return $is[0] === true && $is[1] === true ? true : false;
    }

    //获取关键列表
    public function keywordsList($arr = []){
        $where = "";
        foreach ($arr as $val){//遍历分站集合
            $where .= " topic like '%".$val."%' or";
        }
        $where = rtrim($where,"or");
        return $this->field("keywords")->where("keywords","NOT NULL")->where($where)->select();
    }


    //添加图纸配置参数（NEW）
    public function drawingBankConfigAddNew($data){
        $rs = action('Drawings/getDrawingConfig');//自动同步配置参数
        $DrawingConfigurationParameter = config("DrawingConfigurationParameter");//获取图纸配置参数
        $Config = new Config();
        foreach ($data as $DataKey=>$DataVal){
            $attrsData = [];//属性附加数组
            foreach ($DrawingConfigurationParameter as $key=>$val) {//遍历配置参数
                if($DrawingConfigurationParameter["attrs"] == $val){//是否是图纸属性
                    if(!empty($DataVal["attrs"]) && !empty($DataVal["attrsData"])) {//图纸属性不为空
                        $ids = "";
                        foreach ($DataVal["attrsData"] as $ATDKey=>$ATDVal){//遍历图纸属性
                            $id = $Config->getConfigId($ATDVal["config_name"]);//获取配置参数名称
                            $ids .= "[".$id."]";
                            $attrsData[$ATDKey]["config_id"] = $id;
                        }
                        $data[$DataKey][$key] = $ids;
                    }
                }else{
                    $data[$DataKey][$key] = $Config->getConfigId($DataVal[$key."_name"]);//获取配置参数名称
                }
            }
            $data[$DataKey]['attrsData'] = json_encode($attrsData);//转化成为json，属性附加赋值
        }
        return $data;
    }

    //检查图纸是否存在
    public function checkDrawOnly($draw_id = 0,$no = '',$no2 = ''){
        return $this
            ->where(function ($q)use ($draw_id){
                if(!empty($draw_id)){
                    $q->where('draw_id',$draw_id);
                }
            })
            ->where(function ($q)use($no,$no2){
                if(!empty($no)){
                    $q->where('no',$no);
                }
                if(!empty($no2)){
                    $q->where('no2',$no2);
                }
            })
            ->count();
    }

    //更新图纸基础信息
    public function updateAllDrawingBank($data){
        $count = 0;
        foreach ($data as $key => $val){
            $drawing_id = $this->where("no",$val["no"])->where("no2",$val["no2"])->value("drawing_id");
            if(!empty($drawing_id)) {
                if ($this->mySave($val, "drawing_id", $drawing_id)) {
                    ++$count;
                }
            }
        }
        return $count;
    }
}